今天會把首頁的CollectView建立好,首先,先建立三個Cocoa Touch Class,都是CollectionViewCell:
import UIKit
class TypeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imgCell: UIImageView!
static var identifer = "TypeCollectionViewCell"
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
class MoreImformationsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imgCell: UIImageView!
static let identifier = "MoreImformationsCollectionViewCell"
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
import UIKit
class ResaurantCollectionViewCell: UICollectionViewCell {
// MARK: - IBOutlet
@IBOutlet weak var imgCell: UIImageView!
@IBOutlet weak var btnCell: UIButton!
// MARK: - Variables
static let identifier = "ResaurantCollectionViewCell"
// MARK: - LifeCycle
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
// MARK: - UI Setting
func setupUI() {
btnCell.setTitle(" ", for: .normal)
}
// MARK: - IBAction
@IBAction func btnClick(_ sender: Any) {
print("123")
}
}
接著到主畫面設定:
covFoodType.tag = 0
covFoodType.dataSource = self
covFoodType.delegate = self
covFoodType.register(ResaurantCollectionViewCell.loadFromNib(), forCellWithReuseIdentifier: ResaurantCollectionViewCell.identifier)
covResaurant.tag = 1
covResaurant.delegate = self
covResaurant.dataSource = self
covResaurant.register(TypeCollectionViewCell.loadFromNib(), forCellWithReuseIdentifier: TypeCollectionViewCell.identifer)
covMoreImformations.tag = 2
covMoreImformations.delegate = self
covMoreImformations.dataSource = self
covMoreImformations.register(MoreImformationsCollectionViewCell.loadFromNib(), forCellWithReuseIdentifier: MoreImformationsCollectionViewCell.identifier)
然後是Delegate:
extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch collectionView.tag {
case 0:
return 4
case 1:
return 4
case 2:
return 4
default:
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch collectionView.tag {
case 0:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ResaurantCollectionViewCell.identifier, for: indexPath) as!
ResaurantCollectionViewCell
cell.imgCell.image = UIImage(named: foodType[indexPath.row])
return cell
case 1:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TypeCollectionViewCell.identifer, for: indexPath) as!
TypeCollectionViewCell
cell.imgCell.image = UIImage(named: foodType[indexPath.row])
return cell
case 2:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MoreImformationsCollectionViewCell.identifier, for: indexPath) as!
MoreImformationsCollectionViewCell
cell.imgCell.image = UIImage(named: foodType[indexPath.row])
return cell
default:
return UICollectionViewCell()
}
return UICollectionViewCell()
}
}